<template>
    <div>
      <div v-if="isLoading === 1" class="chat_loading">
        <van-loading >会话加载中...</van-loading>
      </div>
      <template v-else-if="isLoading === 2">

        <TUIKit
          :SDKAppID="appId"
          :userID="userId"
          :userSig="userSig"
          :conversationID="conversationID"
          :style="{  height: 'var(--vhHeight)' }"
        >
          <TUIChat><h1></h1></TUIChat>
        </TUIKit>
      </template>
        
      <div v-else>加载失败</div>
    </div>
</template>
<script lang="ts" setup>
import { TUIKit, TUIChat, genTestUserSig } from "../../TUIKit";
import { getImSigByUser, getSessionStatus, getOrCreateSession } from '@/apis/chatLine'
import {setToken} from '@/utils/auth'
import TUIChatEngine from '@tencentcloud/chat-uikit-engine';

import { vantComponents } from "@/hooks/useVantModel";

const { showToast } = vantComponents();
const route = useRoute();
const userSig = ref('')
const userId = ref('')
const conversationID = ref('')

const isLoading = ref<null | number>(1)

const appId = ref(import.meta.env.VITE_APP_IM_APPID)

// 登录逻辑 
async function loginChat() {
  const userId_q = route.query.userId as string
  const targetId_q = route.query.targetId as string
  const token = route.query.token 
  const orderId = route.query.orderId
  console.log(userId_q,targetId_q,token)
  if (!userId_q || !token) {
    showToast('登录失败')
    isLoading.value = null as unknown as number
    return 
  };
  setToken(token)
  try {
    const userDatas = await getImSigByUser({ userId: userId_q })
    const { sysUserInfo } = userDatas.data
    const role = sysUserInfo.roles[0].roleKey === 'sys_patient'

    let params = {}

    if (role) { 
      params.patientId = userId_q;
      params.pharmacistId = targetId_q
    } else {
      // patientId = targetId_q;
      // pharmacistId = userId_q
      if (!orderId) { 
        showToast('未找到订单')
        return
      }
      params.id = orderId
    }

    const sessionStatus = await getSessionStatus(params)
 

    localStorage.setItem('userInfos', JSON.stringify(sysUserInfo))
    localStorage.setItem('roles', JSON.stringify(sysUserInfo.roles[0].roleKey || {}))
    localStorage.setItem('sessionStatus', sessionStatus.data === null ? '{}' : JSON.stringify(sessionStatus.data))
    
    if (role) {
      // 如果是患者身份
      console.log(sessionStatus)
      if (sessionStatus.data === null) { 
        // 不存在订单，则新建一条
        getOrCreateSession(params).then(res => {
          localStorage.setItem('sessionStatus',res.data === null?'{}':JSON.stringify(res.data))
          connetChat(userId_q,userDatas.data.sig,targetId_q)
        })
      } else {
        connetChat(userId_q,userDatas.data.sig,targetId_q)
      }

      // userId.value = userId_q
      // userSig.value = userDatas.data.sig
      // conversationID.value = 'C2C' + targetId_q
      // isLoading.value = 2 
      
    } else if(sysUserInfo.roles[0].roleKey === 'sys_pharmacist') {
      // 如果是药师身份
      connetChat(userId_q,userDatas.data.sig,targetId_q)
  }
  // await getImSigByUser({ userId: userId_q })
  // 信令应从后台获取  这里模拟前台获取
  // const options1 = genTestUserSig({
  //       SDKAppID:1600054024,
  //       secretKey:'86fefe04bb9ea706e9e919b766be3151e313db10416f0a6df426a17cbcfe0739',
  //       userID: userId_q,
  // });
  // console.log(userDatas.data.sig,options1.userSig,'aaa')
 
  
  } catch (error) {
    showToast('用户信息错误!')
    isLoading.value = null
  }
  

}

function connetChat(userId_q,sig,targetId_q) {
  userId.value = userId_q
      userSig.value = sig
      conversationID.value = 'C2C' + targetId_q
      isLoading.value = 2 
}


onMounted(() => {
  loginChat()

})

</script>

<style lang="scss" scoped>
.chat_loading{
  height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>
